<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

class JFX_Module_Imager_Export extends JFX_Data_File
{
	public $folders = array();
	public $compressedFilepath = '';

	public function __construct(){
		
	}

	public function addFolder($folderPath){
		$this->folders[] = $folderPath;
	}

	public function getFolders(){
		return $this->folders;
	}

	public function import($filepath){
		if(file_exists($filepath)){
			$IMAGE_MODULE = JFX::registry('JFX_Module_Imager');
			$this->compressedFilepath = $filepath;
			$zip = new ZipArchive();
			$zip->open($this->compressedFilepath);
			$folderConfig = unserialize($zip->getFromIndex(0));
			for($i=0; $i<=$folderConfig['num_files']; $i++){
				$file = unserialize($zip->getFromIndex($i+1));
				if($file instanceof JFX_Data_File){
					$file->setContents($file->contents);
					unset($file->contents);
					$file->save();
					$path = $file->meta['filepath'];
					$IMAGE_MODULE->addFolderPath($path);
				}
			}
		}
	}

	public function compress($dirname, $dirnameTitle){
		$CONFIG = JFX::registry('config');
		$this->compressedFilepath = $CONFIG->tmpDir.'/jfxmoduleimager.'.$dirname.rand().'.zip';

		$zip = new ZipArchive();
		$zip->open($this->compressedFilepath, ZipArchive::CREATE);
		
		$numFiles = 0;
		foreach($this->folders as $folder){
			foreach($folder->files as $file){
				$numFiles++;
			}
		}

		$folderConfig = array(
		    'num_files' => $numFiles,
		    'dirname_title' => $dirnameTitle,
		    'dirname' => $dirname
		);

		$zip->addFromString('folder_config.conf', serialize($folderConfig));

		foreach($this->folders as $folder){
			foreach($folder->files as $file){
				$file->contents = $file->getContents();
				$zip->addFromString($file->meta['filename'], serialize($file));
				unset($file->contents);
			}
		}

		$zip->close();
		
	}

	public function printFile($filename){
		while(ob_get_level()>0){
			ob_end_clean();
		}
		header('content-type: application/zip');
		header('content-disposition: attachment; filename="'.$filename.'"');
		readfile($this->compressedFilepath);
		exit;
	}

}